package com.carol.backend.service;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 自定义消息存储服务
 * 在Redis中保存消息内容和时间戳信息
 * 
 * @author carol
 */
@Slf4j
@Service
public class CustomMessageStorageService {
    
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    private static final String MESSAGE_KEY_PREFIX = "chat:messages:";
    private static final int MESSAGE_TTL_DAYS = 30; // 消息保存30天
    
    /**
     * 保存消息到Redis
     */
    public void saveMessage(String conversationId, Message message, boolean isUser) {
        try {
            String messageKey = MESSAGE_KEY_PREFIX + conversationId;
            
            // 创建消息存储对象
            StoredMessage storedMessage = new StoredMessage();
            storedMessage.setContent(extractMessageContent(message));
            storedMessage.setIsUser(isUser);
            storedMessage.setTimestamp(System.currentTimeMillis());
            storedMessage.setCreatedTime(LocalDateTime.now());
            storedMessage.setMessageType(isUser ? "USER" : "ASSISTANT");
            
            // 序列化为JSON
            String messageJson = objectMapper.writeValueAsString(storedMessage);
            
            // 添加到Redis列表
            redisTemplate.opsForList().rightPush(messageKey, messageJson);
            
            // 设置过期时间
            redisTemplate.expire(messageKey, MESSAGE_TTL_DAYS, TimeUnit.DAYS);
            
            log.info("[CustomMessageStorage] 保存消息: conversationId={}, isUser={}, timestamp={}", 
                    conversationId, isUser, storedMessage.getTimestamp());
            
        } catch (JsonProcessingException e) {
            log.error("[CustomMessageStorage] 序列化消息失败: conversationId={}, error={}", 
                    conversationId, e.getMessage(), e);
        }
    }
    
    /**
     * 从Redis获取消息历史
     */
    public List<StoredMessage> getMessages(String conversationId) {
        try {
            String messageKey = MESSAGE_KEY_PREFIX + conversationId;
            List<String> messageJsonList = redisTemplate.opsForList().range(messageKey, 0, -1);
            
            List<StoredMessage> messages = new ArrayList<>();
            if (messageJsonList != null) {
                for (String messageJson : messageJsonList) {
                    try {
                        StoredMessage message = objectMapper.readValue(messageJson, StoredMessage.class);
                        messages.add(message);
                    } catch (JsonProcessingException e) {
                        log.warn("[CustomMessageStorage] 反序列化消息失败: {}", e.getMessage());
                    }
                }
            }
            
            log.info("[CustomMessageStorage] 获取消息历史: conversationId={}, count={}", 
                    conversationId, messages.size());
            return messages;
            
        } catch (Exception e) {
            log.error("[CustomMessageStorage] 获取消息历史失败: conversationId={}, error={}", 
                    conversationId, e.getMessage(), e);
            return new ArrayList<>();
        }
    }
    
    /**
     * 清空会话消息
     */
    public void clearMessages(String conversationId) {
        try {
            String messageKey = MESSAGE_KEY_PREFIX + conversationId;
            redisTemplate.delete(messageKey);
            log.info("[CustomMessageStorage] 清空消息: conversationId={}", conversationId);
        } catch (Exception e) {
            log.error("[CustomMessageStorage] 清空消息失败: conversationId={}, error={}", 
                    conversationId, e.getMessage(), e);
        }
    }
    
    /**
     * 提取消息内容
     */
    private String extractMessageContent(Message message) {
        // 使用反射或toString来获取消息内容
        try {
            // 尝试使用反射获取content字段
            if (message instanceof UserMessage) {
                // UserMessage通常有content字段
                return message.toString(); // 暂时使用toString
            } else if (message instanceof AssistantMessage) {
                // AssistantMessage通常有content字段
                return message.toString(); // 暂时使用toString
            } else {
                return message.toString();
            }
        } catch (Exception e) {
            log.warn("[CustomMessageStorage] 无法获取消息内容，使用toString: {}", e.getMessage());
            return message.toString();
        }
    }
    
    /**
     * 存储的消息对象
     */
    @Data
    public static class StoredMessage {
        /**
         * 消息内容
         */
        private String content;
        
        /**
         * 是否为用户消息
         */
        private Boolean isUser;
        
        /**
         * 时间戳（毫秒）
         */
        private Long timestamp;
        
        /**
         * 创建时间
         */
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime createdTime;
        
        /**
         * 消息类型
         */
        private String messageType;
    }
}
